from flask import Blueprint, request, session

from src.api.https import fail_api, success_api
from src.model.CLikeModel import CLikeModel
from src.model.CommentModel import CommentModel
from src.utils.check_require import login_required
from datetime import datetime
from src.init.init_db import db
from src.utils.comment_tool import CommentTool
from src.utils.time_tool import get_china_time

comments_api = Blueprint('comments_api', __name__, url_prefix='/api/comments')

ctool = CommentTool()


@comments_api.post('/add')
@login_required
def add_comment():
    # 添加评论
    aid = request.json['aid']
    content = request.json['content']
    uid = session['uid']
    fcid = request.json.get('fcid')
    if not fcid:
        fcid = None

    comment = CommentModel(uid=uid, aid=aid, fcid=fcid, content=content, createtime=get_china_time())
    db.session.add(comment)
    db.session.commit()

    return success_api("添加评论成功")


@comments_api.post('/delete')
@login_required
def delete_comment():
    # 删除评论
    cid = request.json['cid']
    comment = CommentModel.query.filter_by(cid=cid).first()
    if comment.fcid is None:
        sub_comments = CommentModel.query.filter_by(fcid=cid)
        if sub_comments is not None:
            for sub_comment in sub_comments:
                db.session.delete(sub_comment)
    db.session.delete(comment)
    db.session.commit()

    return success_api("删除评论成功")


@comments_api.post('/likeComment')
@login_required
def like_comment():
    # 点赞评论
    # 点赞文章
    cid = request.json['cid']
    uid = session['uid']

    if CLikeModel.query.filter_by(cid=cid, uid=uid).first() is not None:
        return fail_api("不可重复点赞")

    clike = CLikeModel(cid=cid, uid=uid)
    db.session.add(clike)
    db.session.commit()

    return success_api("评论点赞完成")


@comments_api.post('/cancelLikeComment')
@login_required
def cancel_like_comment():
    # 取消评论点赞
    cid = request.json['cid']
    uid = session['uid']

    if CLikeModel.query.filter_by(cid=cid, uid=uid).first() is None:
        return fail_api("当前未点赞")

    clike = CLikeModel.query.filter_by(cid=cid, uid=uid).first()
    db.session.delete(clike)
    db.session.commit()

    return success_api("评论点赞删除完成")
